package guo.xungengauth.service.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import guo.xungengauth.service.WeiboService;
import guo.xungengauth.vo.TokenOthers;
import guo.xungengauth.vo.WeiboToken;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class WeiboServiceImpl implements WeiboService {

    @Override
    public TokenOthers getWBToken(WeiboToken weiboToken) {
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();

        RequestBody requestBody = RequestBody.create(mediaType, JSON.toJSONString(weiboToken));

        Request request = new Request.Builder()
                .url("https://api.weibo.com/oauth2/access_token?client_id="+weiboToken.getClientId()+"&client_secret="+weiboToken.getClientSecret()+"&grant_type=authorization_code&redirect_uri="+weiboToken.getRedirectUrI()+"&code="+weiboToken.getCode())
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            System.out.println(string);
            TokenOthers tokenOthers = JSON.parseObject(string, new TypeReference<TokenOthers>() {
            });
            return tokenOthers;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
